/**
 * Created by Administrator on 2014/8/19.
 */

var crypto = require('crypto');
var wxConfig = require('./config');
function sha1(str) {
    var md5sum = crypto.createHash('sha1');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}

function wxCrypto(query){

    //消息真实性校验：http://mp.weixin.qq.com/wiki/index.php?title=%E9%AA%8C%E8%AF%81%E6%B6%88%E6%81%AF%E7%9C%9F%E5%AE%9E%E6%80%A7
    //微信加密签名
    var signature = query.signature;

    var echostr = query.echostr; //随机字符串
    var timestamp = query['timestamp'];    //时间戳
    var nonce = query.nonce;   //随机数

    /*
     * 加密/校验流程如下：
     1. 将token、timestamp、nonce三个参数进行字典序排序
     2. 将三个参数字符串拼接成一个字符串进行sha1加密
     3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     * */
    var oriArray = new Array();
    oriArray[0] = nonce;
    oriArray[1] = timestamp;
    oriArray[2] = wxConfig.token;//这里填写你的token
    oriArray.sort();
    var original = oriArray[0]+oriArray[1]+oriArray[2];
    var scyptoString = sha1(original);
    return scyptoString;
}

module.exports = wxCrypto;